<?php


namespace catchAdmin\storehouse\controller;

use catchAdmin\stock\model\Stock;
use catcher\base\CatchController;
use catcher\base\CatchRequest as Request;
use catchAdmin\storehouse\model\InventoryOperationRecord as InventoryOperationRecordModel;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\library\client\Response;
use think\Exception;
use think\facade\Db;
use catchAdmin\storehouse\excl\inventoryOperationRecordExport;
use think\facade\Filesystem;
use catcher\library\excel\Excel;

class InventoryOperationRecord extends CatchController
{
    protected $inventoryOperationRecordModel;
    const ORDER_TYPE_RK = 1;
    const ORDER_TYPE_CX = 2;
    const ORDER_TYPE_CJ = 3;
    const ORDER_TYPE_YK = 4;
    const ORDER_TYPE_CK = 5;

    public function __construct(InventoryOperationRecordModel $inventoryOperationRecordModel)
    {
        $this->inventoryOperationRecordModel = $inventoryOperationRecordModel;
    }

    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->inventoryOperationRecordModel->getList($user['tenant_id']));
    }

    public function write($order_type,$order_id,$extend=[]){
        $user = (new CatchAuth())->user();
        $data = [];
        $data['tenant_id'] = $user->tenant_id;
        $data['creator_id'] = $user->id;
        $data['stock_id'] = '';
        $data['box_id'] = '';
        $data['slice_id'] = '';
        $data['ext_json'] = json_encode([]);

        try {
            if($order_type == self::ORDER_TYPE_RK){
                $data['order_type'] =  self::ORDER_TYPE_RK;

                $warehousing_son_result = Db::table('db_warehousing_son')->where('warehousing_son_id',$order_id)->find();
                $warehousing_result = Db::table('db_warehousing')->where('warehousing_id',$warehousing_son_result['warehousing_id'])->find();

                $data['order_pid'] = $warehousing_son_result['warehousing_id'];
                $data['order_id'] = $warehousing_son_result['warehousing_son_id'];

                //操作的这个库存是来自哪一个订单的
                $data['warehousing_id'] = $warehousing_son_result['warehousing_id'];
                $data['warehousing_son_id'] = $warehousing_son_result['warehousing_son_id'];

                $data['goods_name'] = $warehousing_son_result['goods_name'];
                $data['goods_id'] = $warehousing_son_result['goods_id'];

                //入库保存下，库存号和托盘号
                //$data['stock_id'] = implode(',' , (new Stock)->getStockIdsByWarehousingSonId($warehousing_son_result['warehousing_son_id']));
                //$data['tray_id'] = implode(',', (new \catchAdmin\storehouse\model\Tray())->getTrayIdsByWarehousingSonId($warehousing_son_result['warehousing_son_id']));

                //$data['tray_number'] = $warehousing_son_result['tray_number'];
                //$data['box_number'] = $warehousing_son_result['box_number'];
                //$data['number'] = $warehousing_son_result['number'];

                $data['packing_id'] = $warehousing_son_result['packing_id'];

                $packing_result = Db::table('db_packing')->where('packing_id',$warehousing_son_result['packing_id'])->find();
                $unit_result = Db::table('db_unit')->where('unit_code',$packing_result['unit_id'])->find();

                $packing_total = $packing_result['packing_num'] * $packing_result['layup_num'];
                $data['packing_specification'] = "1托/{$packing_result['layup_num']}{$packing_result['unit_name']}/{$packing_total}片";

                $data['project_id'] = $warehousing_result['project_id'];
                $data['project_client'] = $warehousing_result['project_client'];

                //增加 客户业务单号 customer_business_number
                $data['customer_business_number'] = $warehousing_result['customer_business_number'];

            }elseif($order_type == self::ORDER_TYPE_CX || $order_type == self::ORDER_TYPE_CJ){
                $data['order_type'] =  $order_type;

                $stock_result = Db::table('db_stock')->where('stock_id',$extend['stock_id'])->find();

                $data['order_pid'] = $order_id;
                $data['order_id'] = $order_id;

                //操作的这个库存是来自哪一个订单的
                $data['warehousing_id'] = $stock_result['warehousing_id'];
                $data['warehousing_son_id'] = $stock_result['warehousing_son_id'];

                $data['goods_name'] = $stock_result['goods_name'];
                $data['goods_id'] = $stock_result['goods_id'];
                $data['packing_id'] = $stock_result['packing_id'];

                $packing_result = Db::table('db_packing')->where('packing_id',$stock_result['packing_id'])->find();
                $unit_result = Db::table('db_unit')->where('unit_code',$packing_result['unit_id'])->find();

                $packing_total = $packing_result['packing_num'] * $packing_result['layup_num'];
                $data['packing_specification'] = "1托/{$packing_result['layup_num']}{$packing_result['unit_name']}/{$packing_total}片";

                $data['project_id'] = $stock_result['project_id'];
                $data['project_client'] = $stock_result['project_client'];
            }elseif ($order_type == self::ORDER_TYPE_YK){
                $data['order_type'] =  $order_type;

                $move_son_result = Db::table('db_move')->where('move_id',$order_id)->find();

                $stock_result = Db::table('db_stock')->where('stock_id',$move_son_result['stock_id'])->find();

                $data['order_pid'] = $move_son_result['move_code'];
                $data['order_id'] = $move_son_result['move_id'];

                //操作的这个库存是来自哪一个订单的
                $data['warehousing_id'] = $stock_result['warehousing_id'];
                $data['warehousing_son_id'] = $stock_result['warehousing_son_id'];

                $data['goods_name'] = $stock_result['goods_name'];
                $data['goods_id'] = $stock_result['goods_id'];
                $data['packing_id'] = $stock_result['packing_id'];

                $ext_json_arr = json_decode($extend['ext_json'],true);

                $data['tray_number'] = $ext_json_arr['tray_number'];

                $data['number'] = (int)array_sum([$ext_json_arr['Good_Qty'], $ext_json_arr['Hold_Qty'],$ext_json_arr['NG_Qty']]);
                $data['box_number'] = ceil($data['number'] /  $ext_json_arr['packing_num']);

                $data['stock_id'] = $ext_json_arr['stock_id'];
                $data['tray_id'] = $ext_json_arr['tray_id'];
                $data['box_id'] = $ext_json_arr['box_id'];
                $data['slice_id'] = $ext_json_arr['slice_id'];


                $packing_result = Db::table('db_packing')->where('packing_id',$stock_result['packing_id'])->find();
                $unit_result = Db::table('db_unit')->where('unit_code',$packing_result['unit_id'])->find();

                $packing_total = $packing_result['packing_num'] * $packing_result['layup_num'];
                $data['packing_specification'] = "1托/{$packing_result['layup_num']}{$packing_result['unit_name']}/{$packing_total}片";

                $data['project_id'] = $stock_result['project_id'];
                $data['project_client'] = $stock_result['project_client'];

            }elseif ($order_type == self::ORDER_TYPE_CK){
                $data['order_type'] =  $order_type;

                $warehouse_out_son_arr = Db::table('db_pick')->where([
                    ['warehouse_out_son_id','=',$order_id],
                    ['status','=',1]
                ])->select()->toArray();

                $stock_ids = [];
                $warehousing_ids = [];
                $warehousing_son_ids = [];

                foreach ($warehouse_out_son_arr as $key => $value){
                    $stock = Db::table('db_stock')->where('stock_id',$value['stock_id'])->find();
                    $stock_ids[] = $stock['stock_id'];
                    $warehousing_ids[] = $stock['warehousing_id'];
                    $warehousing_son_ids[] = $stock['warehousing_son_id'];
                }

                $warehouse_out_son_result = Db::table('db_warehouse_out_son')->where('warehouse_out_son_id',$order_id)->find();
                $warehouse_out_result =  Db::table('db_warehouse_out')->where('warehouse_out_id',$warehouse_out_son_result['warehouse_out_id'])->find();

                
                $data['order_pid'] = $warehouse_out_son_result['warehouse_out_id'];
                $data['order_id'] = $warehouse_out_son_result['warehouse_out_son_id'];

                //操作的这个库存是来自哪一个订单的
                $data['warehousing_id'] = implode(',',$warehousing_ids);
                $data['warehousing_son_id'] = implode(',',$warehousing_son_ids);
                $data['stock_id'] = implode(',',$stock_ids);

                //出库记录。托盘号，箱号，片号
                $pick_result = Db::table('db_pick')
                    ->field('tray_id,box_id,slice_id')
                    ->where('status',1)
                    ->where('deleted_at',0)
                    ->where('warehouse_out_son_id',$warehouse_out_son_result['warehouse_out_son_id'])
                    ->select()->toArray();

                $data['tray_id'] = implode(',',array_column($pick_result,'tray_id'));
                $data['box_id'] = implode(',',array_filter(array_column($pick_result,'box_id')));
                $data['slice_id'] = implode(',',array_filter(array_column($pick_result,'slice_id')));

                $data['goods_name'] = $warehouse_out_son_result['goods_name'];
                $data['goods_id'] = $warehouse_out_son_result['goods_id'];
                $data['packing_id'] = $warehouse_out_son_result['packing_id'];

//                $data['number'] = $warehouse_out_son_result['number'];
                //$ext_json_arr = json_decode($extend['ext_json'],true);
                $data['number'] = $extend['number'];

                $packing_result = Db::table('db_packing')->where('packing_id', $data['packing_id'])->find();
                $unit_result = Db::table('db_unit')->where('unit_code',$packing_result['unit_id'])->find();

                $packing_total = $packing_result['packing_num'] * $packing_result['layup_num'];
                $data['packing_specification'] = "1托/{$packing_result['layup_num']}{$packing_result['unit_name']}/{$packing_total}片";

                $data['project_id'] = $warehouse_out_result['project_id'];
                $data['project_client'] = $warehouse_out_result['project_client'];

                $data['box_number'] = ceil($data['number'] /  $packing_result['packing_num']);
                $data['tray_number'] = ceil($data['number'] / $packing_total );

                //增加 客户业务单号 customer_business_number
                $data['customer_business_number'] = $warehouse_out_result['customer_business_number'];
            }

            //整理附加数据
            if(!empty($extend)){
                foreach ($extend as $key => $value){
                    if(in_array($key,[
                        'id',
                        'created_at',
                        'updated_at',
                        'deleted_at',
                        'tenant_id',
                        'creator_id'
                    ])){
                        continue;
                    }
                    $data[$key] = $value;
                }
            }

            if($this->inventoryOperationRecordModel->createBy($data)){
                return true;
            }else{
                return false;
            }

        }catch (\Exception $exception){
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * 导出库存操作记录
     *
     * @param Excel $excel
     * @param inventoryOperationRecordExport $inventoryOperationRecordExport
     * @return \think\response\Json
     */
    public function export(Excel $excel, inventoryOperationRecordExport $inventoryOperationRecordExport)
    {
        return CatchResponse::success($excel->save($inventoryOperationRecordExport, 'export/inventory-operation-records'));
    }
}